<script setup>

import {computed, getCurrentInstance, ref} from "vue";
import {getToken} from "@/utils/auth";
import {AdminToken} from "@/utils/constant";
import config from "@/utils/config";

const {proxy} = getCurrentInstance()
const props = defineProps({
  // 上传文件类型
  type: {
    type: Number,
    default: 1
  },
  // 是否支持多选
  multiple: {
    type: Boolean,
    default: true
  },
  // 多选时最大数量
  limit: {
    type: Number,
    default: 10
  },
  // 上传时额外参数
  data: {
    type: Object,
    default: {}
  },
  // 是否显示上传进度
  showProgress: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['change', 'error', 'success', 'allSuccess'])
const fileList = ref([]);
const uploadRef = ref();
const action = ref(import.meta.env.VITE_IMG_URL + '/upload')
const headers = computed(() => ({
  [AdminToken]: getToken(AdminToken)
}))
const visible = ref(false)
let uploadLen = 0;

const handleProgress = () => {
  visible.value = true;
}

const handleSuccess = ({file, response: resp}) => {
  uploadLen++;
  if (uploadLen === fileList.value.length) {
    uploadLen = 0;
    fileList.value = [];
    emit('allSuccess');
  }
  emit('change', file);
  // console.log(resp)
  if (resp.code === 200) {
    proxy.$modal.okNotify('上传成功')
    visible.value = false;
    emit('success', resp);
  }
  if (resp.code === 500) {
    handleError(file)
    proxy.$modal.errorNotify(resp.msg)
  }
}

const handleExceed = () => {
  proxy.$modal.errorNotify('上传文件数量不能超过' + props.limit + '个')
}

const handleError = (item) => {
  uploadLen++;
  if (uploadLen === fileList.value.length) {
    uploadLen = 0;
    fileList.value = [];
    emit('allSuccess');
  }
  proxy.$modal.errorNotify(`${item.name}文件上传失败`)
  uploadRef.value?.abort(item);
  visible.value = false;
  emit('change', item);
  emit('error', item  );
}

const handleClose = () => {
  fileList.value.forEach(item =>{
    uploadRef.value?.abort(item)
  })
  fileList.value = []
  visible.value = false
}

const getAccept = computed(() => {
  switch (props.type) {
    case 1:
      return config.acceptImgType.join(',')
    case 2:
      return config.acceptVideoType.join(',')
    case 3:
      return config.acceptFileType.join(',')
  }
})
</script>

<template>
  <div class="upload">
    <a-upload
        v-model:file-list="fileList"
        ref="uploadRef"
        :action="action"
        :multiple="multiple"
        :limit="limit"
        :show-file-list="false"
        :headers="headers"
        :data="data"
        @progress="handleProgress"
        @success="handleSuccess"
        @exceed-limit="handleExceed"
        @error="handleError"
        :accept="getAccept"
    >
      <slot/>
    </a-upload>
    <a-modal
        v-if="showProgress && fileList.length"
        v-model:visible="visible"
        title="上传进度"
        :close-on-click-modal="false"
        width="500px"
        :mask="false"
        @close="handleClose"
        @before-close="handleClose"
        :footer="false">
      <div class="file-list p-4">
        <template v-for="(item,index) in fileList" :key="index">
          <div class="mb-5">
            <div>{{ item.name }}</div>
            <div class="flex-1">
              <a-progress
                  :percent="item.percent"/>
            </div>
          </div>
        </template>
      </div>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">

</style>
